from __future__ import with_statement

import os
import random
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.http import Http404, HttpResponse
from django.shortcuts import render_to_response
from streamux.radio import daemon
from streamux.radio import icecast
from streamux.radio import liq
from streamux.radio import models

def home(request):
    try:
        c = liq.LiquidSoap()
    except liq.LiquidSoapCommunicationError:
        c = None

    icecast_stats = icecast.metadata()
    icecast_alive = (icecast_stats is not None and
                     'ogg' in icecast_stats and
                     'mp3' in icecast_stats)

    stats = {
        'liq_alive': c is not None,
        'liq_uptime': (c.uptime() if c else None),
        'liq_meta': (c.metadata() if c else None),
        'daemon_alive': daemon.alive(),
        'icecast_alive': icecast_alive,
        'icecast_stats': icecast_stats or {},
        'tracks': models.Track.objects.count(),
        'artists': models.Artist.objects.count(),
        'albums': models.Album.objects.count(),
        }

    return render_to_response('home.html', stats)

def autodj_next(request):
    if request.META['REMOTE_ADDR'] != '127.0.0.1':
        raise Http404()

    num = models.Track.objects.count()
    track = models.Track.objects.all()[random.randint(0, num-1)]

    meta = {
        'title': track.name,
        'artist': track.artist.name,
        }
    if track.album:
        meta['album'] = track.album.name

    meta = ','.join('%s="%s"' % (k,v) for k,v in meta.iteritems())
    filepath = settings.MUSIC_DIR + track.file

    out = 'annotate:%s:%s' % (meta, filepath)

    return HttpResponse(out)
